<?php
$caption = BUtils::T('profile_lbl');
$this->pageTitle = Yii::app()->name . ' - ' . $caption;

//make categories for merchants
$categories = MerchantObject::Categories();

$edit_btn = BUtils::T('edit_btn');
$delete_btn = BUtils::T('delete_btn');
$search_btn = BUtils::T('search_btn');
$add_hours_btn = BUtils::T('add_hours_btn');

//define array
$aWeekDaysShort = BUtils::WeekDayKeys(7, true);
$aOpenningHours = BUtils::AllHour24();

//set full address
$full_address = '';
if (!empty($model->address)) $full_address = $model->address;
//set lanLng = [];
$full_lanlng = '';
if (!empty($model->latitude) and !empty($model->longitude)) {
	$full_lanlng = "[{$model->latitude}, {$model->longitude}]";
}

//get url_logo
$url_logo = empty($model->url_logo) ? Yii::app()->request->baseUrl . '/images/logo_default.png' : $model->url_logo;
//get url_offer_img
$url_offer_img = empty($model->url_offer_img) ? Yii::app()->request->baseUrl . '/images/default_special_picture.png' : str_replace('thumb_', '', $model->url_offer_img);

//set open hours
$hours_list_op = $hours_list = '';
if (!empty($hours)) {
	//set open hours edit style
	foreach ($hours as $v) {
		$sWeekday = $aWeekDaysShort[$v['week_no']];
		$sHours = $aOpenningHours[$v['open_hour']] . ' - ' . $aOpenningHours[$v['close_hour']];
		$hidValue = $v['week_no'] . ',' . $v['open_hour'] . ',' . $v['close_hour'];
		$hours_list_op .= '<div class="item">
<span class="weekday">'.$sWeekday.'</span>
<span class="hours">'.$sHours.'</span>
<a href="javascript:;" class="remove-hours">'.$delete_btn.'</a>
<input type="hidden" value="'.$hidValue.'" name="business_hours['.$v['week_no'].']" />
</div>';
	}
	//set open hours display style
	$sWeekBuffer = array();
	foreach ($hours as $v) {
		$sWeekday = $aWeekDaysShort[$v['week_no']];
		$sHours = $aOpenningHours[$v['open_hour']] . ' - ' . $aOpenningHours[$v['close_hour']];
		$sWeekBuffer[$sHours][] = $v['week_no'];//add the current week day
	}
	foreach ($sWeekBuffer as $key => $v) {
		$size = count($v);
		if ($size > 1) $sWeekday = $aWeekDaysShort[$v[0]] . ' - ' . $aWeekDaysShort[$v[$size-1]];
		else $sWeekday = $aWeekDaysShort[$v[0]];
		$hours_list .= '<div class="item"><span class="weekday">'.$sWeekday.'</span><span class="hours">'.$key.'</span></div>';
	}
}
?>
<style>
.map_canvas { width: 100%; height: 240px; margin-top:10px;}
.map_canvas:after{content: "Type in an address in the input above."; padding-top: 100px; display: block; text-align: center; font-size: 2em; color: #999;}
</style>
<div class="container prepend-top append-bottom">
	
	<div class="span-13">
		<div class="box_white">
		<div class="biz-form">
			<div class="margin">
				<h3><?php echo $caption; ?></h3>
			</div>
<?php
$form = $this->beginWidget('CActiveForm', array(
	'id'=>'merchant-form',
	//'enableAjaxValidation'=>true,
	'enableClientValidation'=>true,
	'clientOptions'=>array(
		'validateOnSubmit'=>true,
	),
));

//TODO: city and country
if (empty($model->country_code)) $model->country_code = 'FI';
if (empty($model->city)) $model->city = 'Helsinki';

//get url_logo
$url_logo = empty($model->url_logo) ? Yii::app()->request->baseUrl . '/images/logo_default.png' : $model->url_logo;
?>

<div class="fieldswrap">
<div class="fields">
	<div class="block">
		<div class="lbl" id="company_name_lbl"><?php echo $form->labelEx($model,'name'); ?></div>
		<div class="ipt">
			<?php echo $form->textField($model,'name', array('class'=>'auto')); ?>
			<?php echo $form->error($model,'name'); ?>
		</div>
	</div>
	<div class="block">
		<div class="lbl" id="company_logo_lbl"><label><?php echo BUtils::T('company_logo_lbl'); ?></label></div>
		<div class="left" style="margin-right:20px;">
			<a class="pic"><img id="img_logo" src="<?php echo $url_logo; ?>" width="100" alg="logo" /></a>
		</div>
		<div class="left">
<?php $this->widget('ext.EAjaxUpload.EAjaxUpload', array(
	'id' => 'uploadFile',
	'config' => array(
		'buttonName' => BUtils::T('upload_new_picture_eg'),
		'action' => Yii::app()->createUrl('/merchant/uploadLogo'),
		'allowedExtensions'=>array("jpg","jpeg","gif","png"),
		'sizeLimit'=>1*1024*1024,
		'onComplete' => "js:function(id, fileName, responseJSON){ handleUploaded(responseJSON); }",
	),
)); ?>
		</div>
		<div class="clear"></div>
	</div>
	<div class="block">
		<div class="lbl"><?php echo $form->labelEx($model,'category_key'); ?></div>
		<div class="ipt">
			<?php echo $form->dropDownList($model, 'category_key', $categories, array('empty'=>'')); ?>
			<?php echo $form->error($model,'category_key'); ?>
		</div>
		<div class="eg"><?php echo BUtils::T('category_business_eg'); ?></div>
	</div>
</div>
<div class="fields">
	<div class="block">
		<div class="lbl" id="company_address_lbl">
			<label for="MerchantForm_address"><?php echo BUtils::T('location_lbl') ?></label>
		</div>
		<div class="ipt" id="geo-info">

<fieldset class="geo-info" style="display:none;">
	<h3>Address-Details</h3>
	<label>Latitude</label>
	<input name="lat" type="text" value="">
	<label>Longitude</label>
	<input name="lng" type="text" value="">
	<label>Formatted Address</label>
	<input name="formatted_address" type="text" value="">
	<label>Route</label>
	<input name="route" type="text" value="">
	<label>Street Number</label>
	<input name="street_number" type="text" value="">
	<label>Postal Code</label>
	<input name="postal_code" type="text" value="">
	<label>Locality</label>
	<input name="locality" type="text" value="">
	<label>Country Code</label>
	<input name="country_short" type="text" value="">
</fieldset>
<?php
echo $form->hiddenField($model,'latitude');
echo $form->hiddenField($model,'longitude');
echo $form->textField($model,'address', array('style'=>'width:80%'));
?>
			<br />
			<span class="tidy"><?php echo $form->labelEx($model,'address'); ?></span>
			<div class="clear" style="padding-bottom:12px;"></div>
			<span class="tidy">
				<?php echo $form->textField($model,'postcode', array('maxlength'=>10, 'size'=>10)); ?>
				<?php echo $form->labelEx($model,'postcode'); ?>
			</span>
			<span class="tidy">
				<?php echo $form->textField($model,'city', array('size'=>12)); ?>
				<?php echo $form->labelEx($model,'city'); ?>
			</span>
			<span class="tidy">
				<?php echo $form->textField($model,'country_code', array('style'=>'width:183px;', 'readonly'=>'readonly', 'class'=>'gray')); ?>
				<?php echo $form->labelEx($model,'country_code'); ?>
			</span>
			<div class="clear" style="padding-bottom:12px;"></div>
			<span class="tidy">
				<?php echo $form->textField($model,'biz_area', array('size'=>40)); ?>
				<?php echo $form->labelEx($model,'biz_area'); ?>
			</span>
			<div class="clear"></div>
			<div class="map_canvas"></div>
		</div>
		<div class="spc">
			<?php echo $form->error($model,'address'); ?>
			<?php echo $form->error($model,'postcode'); ?>
			<?php echo $form->error($model,'city'); ?>
			<?php echo $form->error($model,'country_code'); ?>
		</div>
	</div>
</div>
<div class="fields">
	<div class="block">
		<div class="lbl" id="company_phone_lbl"><?php echo $form->labelEx($model,'phone'); ?></div>
		<div class="ipt">
			<?php echo $form->textField($model,'phone', array('class'=>'auto')); ?>
			<?php echo $form->error($model,'phone'); ?>
		</div>
		<div class="spc"></div>
	</div>
	<div class="block">
		<div class="lbl" id="open_hours_lbl"><?php echo $form->labelEx($model,'opening'); ?></div>
		<!-- <div class="ipt"><?php echo $form->textArea($model,'opening', array('class'=>'auto')); ?></div> -->
		<div class="ipt" class="hours-select">
			<div id="added-hours" class="added-hours"><?php echo $hours_list_op ?></div>
			<?php echo CHtml::dropDownList('weekday', 7, $aWeekDaysShort, array('class'=>'weekday-op')); ?>
			<?php echo CHtml::dropDownList('hours-open', 9, $aOpenningHours, array('class'=>'hours-open-op')); ?>
			<?php echo CHtml::dropDownList('hours-close', 17, $aOpenningHours, array('class'=>'hours-close-op')); ?>
			<button class="button button-thin button-compliment add-hours" value="submit" type="button"><span><?php echo $add_hours_btn; ?></span></button>
		</div>
		<div class="eg"><?php //echo BUtils::T('opening_hours_eg'); ?></div>
		<div class="spc"></div>
	</div>
	<div class="block" style="display:none;">
		<div class="lbl"><?php echo $form->labelEx($model,'average_price'); ?></div>
		<div class="ipt">
			€ <?php echo $form->textField($model,'average_price', array('size'=>'3')); ?>
			<?php echo $form->error($model,'average_price'); ?>
		</div>
		<div class="spc"></div>
	</div>
</div>
<div class="fields">
	<div class="block">
		<div class="lbl"><?php echo $form->labelEx($model,'url_site'); ?></div>
		<div class="ipt"><?php echo $form->textField($model,'url_site', array('class'=>'auto')); ?></div>
		<div class="eg">e.g. http://www.example.com</div>
		<div class="spc"><?php echo $form->error($model,'url_site'); ?></div>
	</div>
	<div class="block">
		<div class="lbl" id="company_brief_lbl"><?php echo $form->labelEx($model,'brief'); ?></div>
		<div class="ipt"><?php echo $form->textArea($model,'brief', array('class'=>'auto', 'rows'=>5)); ?></div>
		<div class="spc"></div>
	</div>
</div><!-- end of .fields -->
</div><!-- end of .fieldswrap -->

	<div class="margin actions">
		<?php echo CHtml::ajaxSubmitButton(BUtils::T('profile_save_btn'), Yii::app()->createUrl($this->id.'/profile'), array(
			'dataType' => 'json',
			'beforeSend' => 'js:function(){beforeSubmit("#profile-button");}',
			'error' => 'js:function(){errorSubmit("#profile-button");}',
			'success' => 'js:function(data){afterSubmit(data, "#profile-button");}',
		), array('class' => 'button button-huge button-confirm', 'id'=>'profile-button')); ?>
		<?php echo CHtml::button(BUtils::T('cancel_btn'), array('class'=>'button button-huge button-thin', 'onclick'=>'history.go(-1);', 'confirm'=>BUtils::T('cancel_btn_msg'))); ?>
	</div>

<?php $this->endWidget(); ?>
			
		</div><!-- end of <div class="biz-form"> -->
		</div>
	</div>
	
	<div class="span-11 right last">
		<div class="box_white append-bottom">
			<div class="biz-form">
				<h3><?php echo $model->name; ?></h3>
				<div class="fieldswrap">
					<div class="fields mobile">
						<div class="span-3">
							<a class="pic"><img src="<?php echo $url_logo; ?>" width="100" /></a><br />
							<a href="http://yamii.fi/place/<?php echo Yii::app()->user->id; ?>" target="_blank"><?php echo BUtils::T('view_your_page_lbl'); ?></a>
						</div>
						<div class="span-5 last shop">
							<div class="address"><?php echo $model->address . '<br />' . $model->postcode . ' ' . $model->city; ?></div>
							<div class="phone"><?php echo $model->phone; ?></div>
							<div class="link"><?php echo $model->url_site; ?></div>
							<?php if ($model->average_price > 0) { ?>
							<div class="average"><?php echo BUtils::T('average_price_lbl') . ': ' . Yii::app()->locale->numberFormatter->formatCurrency($model->average_price, 'EUR'); ?></div>
							<?php } ?>
						</div>
						<div class="clear"></div>
					</div>
				</div>
				<div class="fieldswrap">
					<div class="fields mobile">
						<div class="fixed-title"><?php echo BUtils::T('opening_hours_lbl'); ?></div>
						<div class="added-hours">
							<?php echo $hours_list; ?>
						</div>
					</div>
				</div>
				<div class="fieldswrap relative">
					<div style="position:absolute; right:5px; top:5px;">
						<a class="button button-small button-confirm" href="<?php echo Yii::app()->createUrl('/merchant/feature'); ?>"><span><?php echo $edit_btn; ?></span></a>
					</div>
					<div class="fields mobile">
						<div class="fixed-title"><?php echo BUtils::T('detail_features_lbl'); ?></div>
						<div class="tags">
<?php
if (!empty($tags)) {
	foreach ($tags as $key => $value) {
		if (!empty($value)) {
			$string = null;
			$array = explode(',', $value);
			foreach ($array as $item) {
				$string .= '<span class="nature-list">' . BUtils::T($item) . '</span>';
			}
			echo '<div style="font-weight:bold;margin-top:10px;">'.BUtils::T($key . '_lbl').':</div><div style="margin-left:40px;">'.$string.'</div>';
		}
	}
} else {
	echo '<div class="eg">
		Help: '. BUtils::T('how_profile_tags_work_eg') . '
	</div>';
}
?>
						</div>
					</div>
				</div>
<?php if (!empty($model->brief)) { ?>
				<div class="fieldswrap">
					<div class="fields mobile">
						<div class="fixed-title"><?php echo BUtils::T('merchant_brief_lbl'); ?></div>
						<div class="opening">
							<p><?php echo nl2br($model->brief); ?></p>
						</div>
					</div>
				</div>
<?php } ?>
			</div>
		</div>
		<?php BHelper::HtmlCompletionTips(); ?>
	</div>
</div>
<script type="text/javascript">
$(function() {
	//add hours
	$('.add-hours').click(function() {
		var weekday_op = $('.weekday-op option:selected');
		var weekday_next_op = weekday_op.next();
		var open_op = $('.hours-open-op option:selected');
		var close_op = $('.hours-close-op option:selected');
		var strHours = open_op.text() + ' - ' + close_op.text();
		var strValue = weekday_op.val() + ',' + open_op.val() + ',' + close_op.val();
		$('#added-hours').append('<div class="item">'
			+'<span class="weekday">'+weekday_op.text()+'</span>'
			+'<span class="hours">' + strHours + '</span>'
			+'<a href="javascript:;" class="remove-hours"><?php echo BUtils::T('delete_btn') ?></a>'
			+'<input type="hidden" value="' + strValue + '" name="business_hours['+weekday_op.val()+']" />'
			+'</div>');
		$('.remove-hours').unbind('click').bind('click', function(){
			$(this).parent().remove();
		});
		//remove all, then select
		$('.weekday-op > option').attr('selected', false);
		weekday_next_op.attr('selected', true);
	});
	$('.remove-hours').unbind('click').bind('click', function(){
		$(this).parent().remove();
	});
	
	//map marker
	var imageIcon = new google.maps.MarkerImage('<?php echo Yii::app()->baseUrl . "/images/markers/pin_{$model->category_key}.png"; ?>',
		new google.maps.Size(32, 37), new google.maps.Point(0,0), new google.maps.Point(16,37));
	var imageShadow = new google.maps.MarkerImage('<?php echo Yii::app()->baseUrl; ?>/images/markers/pin_shadow.png',
		new google.maps.Size(51, 37), new google.maps.Point(0,0), new google.maps.Point(16,37));
	$("#MerchantForm_address").geocomplete({
		map: '.map_canvas',  details: '.geo-info',
		<?php if(!empty($full_lanlng)) echo "location: {$full_lanlng},"; ?>
		markerOptions: {
			draggable: true,
			icon: imageIcon,
			shadow: imageShadow
		}
	}).bind("geocode:result", function(event, result){
		setLocationValues(result);
	}).bind("geocode:dragged", function(event, latLng){
		$('#MerchantForm_latitude').val(latLng.lat());
		$('#MerchantForm_longitude').val(latLng.lng());
		geocoder = new google.maps.Geocoder();
		geocoder.geocode({'latLng': latLng}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				if (results[0]) {
					setLocationValues(results[0]);
				}
			} else {
				alert("Geocoder failed due to: " + status);
			}
		});
	});
});

function handleUploaded(respJSON) {
	if (respJSON.error) {
		$('.qq-upload-button').html('<span>'+respJSON.error+'</span>');
	} else {
		if (respJSON.url_logo) {
			$('#img_logo').attr('src', respJSON.url_logo);
			$('ul.qq-upload-list').delay(1000).html('');
		}
	}
}

function beforeSubmit(eId) {
	$(eId).attr('disabled', true).addClass('button-disabled');
}
function errorSubmit(eId) {
	alert('System error. Please contact us with business@yamii.fi.');
	$(eId).attr('disabled', false).removeClass('button-disabled');
}
function afterSubmit(data, eId) {
	$(eId).removeAttr('disabled').removeClass('button-disabled');
	if (data.success) {
		alert(data.success);
		location.reload();
	} else {
		for (var ele in data) {
			$('#'+ele).focus();
			return;
		}
	}
}

function setLocationValues(loc) {
	var lat = loc.geometry.location.lat();
	var lng = loc.geometry.location.lng();
	var locArray = loc.formatted_address.split(', ');
	if (locArray.length > 2) {
		//console.log(locArray);
		var street_number, address, postal_code, city, country, country_code;
		$.map(loc.address_components, function(obj) {
			switch (obj.types[0]) {
				case 'postal_code':
					postal_code = obj.long_name;
					break;
				case 'country':
					country = obj.long_name;
					country_code = obj.short_name;
					break;
				case 'locality':
				case 'administrative_area_level_3':
				case 'administrative_area_level_1':
					if (city == null) city = obj.long_name;
					break;
				case 'route':
					address = obj.long_name;
					break;
				case 'street_number':
					street_number = obj.long_name;
					break;
			}
		});
		if (country_code != null) {
			$('#MerchantForm_latitude').val(lat);
			$('#MerchantForm_longitude').val(lng);
			$("#MerchantForm_postcode").val(postal_code);
			$("#MerchantForm_city").val(city);
			$("#MerchantForm_country_code").val(country_code);
<?php
if (empty($model->address)) {
	echo "$('#MerchantForm_address').val(locArray[0]);";
} else {
	echo "$('#MerchantForm_address').val('{$model->address}');";
}
?>
		}
	}
}
</script>
<?php
$langcode = Yii::app()->language;
if ($langcode == 'zh_cn') $langcode = 'en';
?>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&language=<?php echo $langcode; ?>"></script>
<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/labs/jquery.geocomplete.min.js"></script>